<template>
  <div class="format-tools">
    <ToolContainer
      tool-name="格式转换"
      title="多格式转换工具"
      description="支持JSON、XML、YAML、CSV等多种数据格式的相互转换"
      :header-icon="Switch"
      icon-color="#E6A23C"
      default-tab="json-xml"
      @tab-change="handleTabChange"
    >
      <template #tabs>
        <!-- JSON/XML转换标签页 -->
        <el-tab-pane label="JSON/XML转换" name="json-xml">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="convert-section">
                <el-form label-width="100px">
                  <el-form-item label="转换方向">
                    <el-radio-group v-model="jsonXmlDirection">
                      <el-radio value="json-to-xml">JSON → XML</el-radio>
                      <el-radio value="xml-to-json">XML → JSON</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item :label="jsonXmlDirection === 'json-to-xml' ? 'JSON数据' : 'XML数据'">
                    <el-input
                      v-model="jsonXmlInput"
                      type="textarea"
                      :rows="10"
                      :placeholder="jsonXmlDirection === 'json-to-xml' ? '请输入JSON数据...' : '请输入XML数据...'"
                    />
                  </el-form-item>
                  <el-form-item v-if="jsonXmlDirection === 'json-to-xml'" label="XML选项">
                    <el-checkbox v-model="xmlOptions.declaration">添加XML声明</el-checkbox>
                    <el-checkbox v-model="xmlOptions.pretty">格式化输出</el-checkbox>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="convertJsonXml"
                :loading="loading"
                :disabled="!jsonXmlInput.trim()"
              >
                开始转换
              </el-button>
              <el-button 
                @click="validateInput"
                :disabled="!jsonXmlInput.trim()"
              >
                验证格式
              </el-button>
              <el-button @click="clearJsonXml">
                清空
              </el-button>
            </template>

            <template #result>
              <div v-if="jsonXmlOutput" class="result-display">
                <h4>转换结果：</h4>
                <el-input
                  v-model="jsonXmlOutput"
                  type="textarea"
                  :rows="10"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('jsonXml')">
                    复制结果
                  </el-button>
                  <el-button @click="downloadResult('jsonXml')">
                    下载文件
                  </el-button>
                  <el-button @click="clearOutput('jsonXml')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- YAML转换标签页 -->
        <el-tab-pane label="YAML转换" name="yaml">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="yaml-section">
                <el-form label-width="100px">
                  <el-form-item label="转换方向">
                    <el-radio-group v-model="yamlDirection">
                      <el-radio value="json-to-yaml">JSON → YAML</el-radio>
                      <el-radio value="yaml-to-json">YAML → JSON</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item :label="yamlDirection === 'json-to-yaml' ? 'JSON数据' : 'YAML数据'">
                    <el-input
                      v-model="yamlInput"
                      type="textarea"
                      :rows="10"
                      :placeholder="yamlDirection === 'json-to-yaml' ? '请输入JSON数据...' : '请输入YAML数据...'"
                    />
                  </el-form-item>
                  <el-form-item v-if="yamlDirection === 'json-to-yaml'" label="YAML选项">
                    <el-form-item label="缩进空格">
                      <el-select v-model="yamlOptions.indent" style="width: 100px;">
                        <el-option label="2" :value="2" />
                        <el-option label="4" :value="4" />
                        <el-option label="8" :value="8" />
                      </el-select>
                    </el-form-item>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="convertYaml"
                :loading="loading"
                :disabled="!yamlInput.trim()"
              >
                开始转换
              </el-button>
              <el-button @click="clearYaml">
                清空
              </el-button>
            </template>

            <template #result>
              <div v-if="yamlOutput" class="result-display">
                <h4>转换结果：</h4>
                <el-input
                  v-model="yamlOutput"
                  type="textarea"
                  :rows="10"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('yaml')">
                    复制结果
                  </el-button>
                  <el-button @click="downloadResult('yaml')">
                    下载文件
                  </el-button>
                  <el-button @click="clearOutput('yaml')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- Excel转换工具标签页 -->
        <el-tab-pane label="Excel转换工具" name="csv">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="csv-section">
                <el-form label-width="120px">
                  <el-form-item label="转换方向">
                    <el-radio-group v-model="csvDirection">
                      <el-radio value="json-to-excel">JSON → Excel</el-radio>
                      <el-radio value="xml-to-excel">XML → Excel</el-radio>
                      <el-radio value="yaml-to-excel">YAML → Excel</el-radio>
                      <el-radio value="csv-to-excel">CSV → Excel</el-radio>
                      <el-radio value="tsv-to-excel">TSV → Excel</el-radio>
                      <el-radio value="text-to-excel">文本 → Excel</el-radio>
                      <el-radio value="excel-to-json">Excel → JSON</el-radio>
                      <el-radio value="url-to-excel">URL数据 → Excel</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  
                  <!-- 文件上传区域 -->
                  <el-form-item v-if="needFileUpload()" label="上传文件">
                    <el-upload
                      ref="uploadRef"
                      :auto-upload="false"
                      :show-file-list="true"
                      :limit="1"
                      :accept="getAcceptTypes()"
                      :on-change="handleFileChange"
                      :on-remove="handleFileRemove"
                    >
                      <el-button type="primary">{{ getUploadButtonText() }}</el-button>
                      <template #tip>
                        <div class="el-upload__tip">
                          {{ getUploadTipText() }}
                        </div>
                      </template>
                    </el-upload>
                  </el-form-item>
                  
                  <!-- URL输入区域 -->
                  <el-form-item v-if="csvDirection === 'url-to-excel'" label="数据URL">
                    <el-input
                      v-model="urlInput"
                      placeholder="请输入返回JSON/CSV数据的API地址..."
                    />
                    <el-form-item label="请求方法" style="margin-top: 12px;">
                      <el-select v-model="urlOptions.method" style="width: 100px;">
                        <el-option label="GET" value="GET" />
                        <el-option label="POST" value="POST" />
                      </el-select>
                    </el-form-item>
                    <el-form-item v-if="urlOptions.method === 'POST'" label="请求体">
                      <el-input
                        v-model="urlOptions.body"
                        type="textarea"
                        :rows="3"
                        placeholder="JSON格式的请求体..."
                      />
                    </el-form-item>
                  </el-form-item>
                  
                  <!-- 输入区域 -->
                  <el-form-item v-if="needTextInput()" :label="getInputLabel()">
                    <el-input
                      v-model="csvInput"
                      type="textarea"
                      :rows="10"
                      :placeholder="getInputPlaceholder()"
                    />
                  </el-form-item>
                  
                  <!-- 显示上传文件内容 -->
                  <el-form-item v-if="uploadedFileContent" label="文件内容预览">
                    <el-input
                      v-model="uploadedFileContent"
                      type="textarea"
                      :rows="8"
                      readonly
                      placeholder="文件内容将在这里显示..."
                    />
                  </el-form-item>
                  
                  <!-- 文本转Excel的特殊选项 -->
                  <el-form-item v-if="csvDirection === 'text-to-excel'" label="文本处理">
                    <el-checkbox v-model="textOptions.splitByLine">按行分割</el-checkbox>
                    <el-checkbox v-model="textOptions.splitBySpace">按空格分列</el-checkbox>
                    <el-checkbox v-model="textOptions.splitByComma">按逗号分列</el-checkbox>
                    <el-form-item label="自定义分隔符">
                      <el-input v-model="textOptions.customDelimiter" style="width: 150px;" placeholder="如：|" />
                    </el-form-item>
                  </el-form-item>
                  
                  <el-form-item label="Excel选项">
                    <el-form-item label="工作表名">
                      <el-input v-model="excelOptions.sheetName" style="width: 150px;" placeholder="Sheet1" />
                    </el-form-item>
                    <el-checkbox v-model="excelOptions.includeHeader">包含表头</el-checkbox>
                    <el-checkbox v-model="excelOptions.autoWidth">自动列宽</el-checkbox>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="convertToExcel"
                :loading="loading"
                :disabled="!canConvert()"
              >
                {{ getConvertButtonText() }}
              </el-button>
              <el-button @click="clearAll">
                清空所有
              </el-button>
              <el-button v-if="csvDirection === 'url-to-excel'" @click="testUrl">
                测试URL
              </el-button>
            </template>

            <template #result>
              <div v-if="csvOutput" class="result-display">
                <h4>转换结果：</h4>
                <!-- 表格预览 -->
                <div v-if="previewData.length > 0" class="preview-section">
                  <h5>数据预览：</h5>
                  <el-table :data="previewData.slice(0, 5)" border style="width: 100%; margin-bottom: 16px;">
                    <el-table-column
                      v-for="(column, index) in previewColumns"
                      :key="index"
                      :prop="column.prop"
                      :label="column.label"
                      :width="column.width"
                    />
                  </el-table>
                  <p class="preview-info">显示前5行数据，共 {{ previewData.length }} 行</p>
                </div>
                
                <!-- 结果文本 -->
                <el-input
                  v-model="csvOutput"
                  type="textarea"
                  :rows="8"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('csv')">
                    复制结果
                  </el-button>
                  <el-button @click="downloadResult('csv')">
                    下载Excel文件
                  </el-button>
                  <el-button @click="downloadAsCSV">
                    下载CSV文件
                  </el-button>
                  <el-button @click="clearOutput('csv')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- 数据格式化标签页 -->
        <el-tab-pane label="数据格式化" name="format">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="format-section">
                <el-form label-width="100px">
                  <el-form-item label="数据类型">
                    <el-select v-model="formatType" style="width: 150px;">
                      <el-option label="JSON" value="json" />
                      <el-option label="XML" value="xml" />
                      <el-option label="SQL" value="sql" />
                      <el-option label="CSS" value="css" />
                      <el-option label="HTML" value="html" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="输入数据">
                    <el-input
                      v-model="formatInput"
                      type="textarea"
                      :rows="12"
                      :placeholder="`请输入${formatType.toUpperCase()}数据...`"
                    />
                  </el-form-item>
                  <el-form-item label="格式选项">
                    <el-form-item label="缩进">
                      <el-select v-model="formatOptions.indent" style="width: 120px;">
                        <el-option label="2个空格" :value="2" />
                        <el-option label="4个空格" :value="4" />
                        <el-option label="Tab缩进" value="tab" />
                      </el-select>
                    </el-form-item>
                    <el-checkbox v-model="formatOptions.minify">压缩输出</el-checkbox>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="formatData"
                :loading="loading"
                :disabled="!formatInput.trim()"
              >
                格式化
              </el-button>
              <el-button 
                type="success" 
                @click="minifyData"
                :loading="loading"
                :disabled="!formatInput.trim()"
              >
                压缩
              </el-button>
              <el-button @click="clearFormat">
                清空
              </el-button>
            </template>

            <template #result>
              <div v-if="formatOutput" class="result-display">
                <h4>格式化结果：</h4>
                <el-input
                  v-model="formatOutput"
                  type="textarea"
                  :rows="12"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('format')">
                    复制结果
                  </el-button>
                  <el-button @click="downloadResult('format')">
                    下载文件
                  </el-button>
                  <el-button @click="clearOutput('format')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>
      </template>
    </ToolContainer>

    <!-- 功能介绍组件 -->
    <FeatureIntro
      :title="featureConfig.title"
      :description="featureConfig.description"
      :header-icon="featureConfig.headerIcon"
      :features="featureConfig.features"
      :initial-visible="showIntro"
      @close="showIntro = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Switch } from '@element-plus/icons-vue'
import ToolContainer from '@/components/ToolContainer.vue'
import ToolSection from '@/components/ToolSection.vue'
import FeatureIntro from '@/components/FeatureIntro.vue'

// 基础数据
const loading = ref(false)
const showIntro = ref(true)

// 本地定义featureConfig，避免循环依赖
const featureConfig = {
  title: '关于格式转换工具',
  description: '强大的格式转换工具集，支持JSON、XML、YAML、CSV等多种数据格式的相互转换，让数据处理变得简单高效。',
  headerIcon: Switch,
  features: [
    {
      title: 'JSON/XML转换',
      icon: Switch,
      color: '#409EFF',
      description: '支持JSON与XML格式的双向转换，保持数据结构完整'
    },
    {
      title: 'YAML转换',
      icon: Switch,
      color: '#67C23A',
      description: '支持YAML与JSON格式互转，配置文件处理首选'
    },
    {
      title: 'Excel转换',
      icon: Switch,
      color: '#E6A23C',
      description: '支持多种格式转Excel，数据分析更便捷'
    },
    {
      title: '数据格式化',
      icon: Switch,
      color: '#F56C6C',
      description: '美化和压缩JSON、XML、CSS、HTML等格式'
    }
  ]
}

// JSON/XML转换相关
const jsonXmlDirection = ref('json-to-xml')
const jsonXmlInput = ref('')
const jsonXmlOutput = ref('')
const xmlOptions = ref({
  declaration: true,
  pretty: true
})

// YAML转换相关
const yamlDirection = ref('json-to-yaml')
const yamlInput = ref('')
const yamlOutput = ref('')
const yamlOptions = ref({
  indent: 2
})

// CSV转换相关
const csvDirection = ref('json-to-excel')
const csvInput = ref('')
const csvOutput = ref('')
const csvOptions = ref({
  delimiter: ',',
  header: true
})

// Excel相关
const uploadedFileContent = ref('')
const uploadRef = ref()
const excelOptions = ref({
  sheetName: 'Sheet1',
  includeHeader: true,
  autoWidth: true
})

// 新增数据变量
const urlInput = ref('')
const urlOptions = ref({
  method: 'GET',
  body: ''
})

const textOptions = ref({
  splitByLine: true,
  splitBySpace: false,
  splitByComma: false,
  customDelimiter: ''
})

const previewData = ref([])
const previewColumns = ref([])

// 数据格式化相关
const formatType = ref('json')
const formatInput = ref('')
const formatOutput = ref('')
const formatOptions = ref({
  indent: 2,
  minify: false
})

// 事件处理
function handleTabChange(tabName: string) {
  console.log('切换到标签页:', tabName)
}

// 文件上传处理
function handleFileChange(file: any) {
  console.log('文件上传触发:', file.name, file.size)
  const fileName = file.name.toLowerCase()
  
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const content = e.target?.result as string
      console.log('文件读取成功，内容长度:', content.length)
      
      if (fileName.endsWith('.csv') || fileName.endsWith('.tsv')) {
        uploadedFileContent.value = content
      } else if (fileName.endsWith('.xml')) {
        uploadedFileContent.value = content
      } else if (fileName.endsWith('.yaml') || fileName.endsWith('.yml')) {
        uploadedFileContent.value = content
      } else if (fileName.endsWith('.txt')) {
        uploadedFileContent.value = content
      } else if (fileName.endsWith('.json')) {
        uploadedFileContent.value = content
      } else if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls')) {
        // Excel文件处理（简化实现）
        uploadedFileContent.value = content
      } else {
        uploadedFileContent.value = content
      }
      
      console.log('设置文件内容完成，长度:', uploadedFileContent.value.length)
      ElMessage.success('文件上传成功')
    } catch (error) {
      console.error('文件读取失败:', error)
      ElMessage.error('文件读取失败：' + error.message)
    }
  }
  
  reader.readAsText(file.raw)
}

// 文件移除处理
function handleFileRemove() {
  console.log('文件被移除')
  uploadedFileContent.value = ''
  ElMessage.info('文件已移除')
}

// 获取输入标签
function getInputLabel(): string {
  switch (csvDirection.value) {
    case 'json-to-csv':
    case 'json-to-excel':
      return 'JSON数据'
    case 'csv-to-json':
      return 'CSV数据'
    default:
      return '输入数据'
  }
}

// 获取输入占位符
function getInputPlaceholder(): string {
  switch (csvDirection.value) {
    case 'json-to-csv':
    case 'json-to-excel':
      return '请输入JSON数组数据...'
    case 'csv-to-json':
      return '请输入CSV数据...'
    default:
      return '请输入数据...'
  }
}

// 检查是否可以转换
function canConvert(): boolean {
  console.log('检查是否可以转换:')
  console.log('- 转换方向:', csvDirection.value)
  console.log('- 需要文件上传:', needFileUpload())
  console.log('- 需要文本输入:', needTextInput())
  console.log('- 上传文件内容长度:', uploadedFileContent.value.length)
  console.log('- 文本输入长度:', csvInput.value.length)
  console.log('- URL输入:', urlInput.value)
  
  // 对于需要文件上传的转换类型
  if (needFileUpload()) {
    const result = !!uploadedFileContent.value
    console.log('- 文件上传检查结果:', result)
    return result
  }
  
  // 对于URL转换
  if (csvDirection.value === 'url-to-excel') {
    const result = !!urlInput.value.trim()
    console.log('- URL检查结果:', result)
    return result
  }
  
  // 对于需要文本输入的转换类型
  if (needTextInput()) {
    const result = !!csvInput.value.trim()
    console.log('- 文本输入检查结果:', result)
    return result
  }
  
  console.log('- 返回false')
  return false
}

// 检查是否需要文件上传
function needFileUpload(): boolean {
  return csvDirection.value === 'excel-to-json' || 
         csvDirection.value === 'xml-to-excel' ||
         csvDirection.value === 'yaml-to-excel' ||
         csvDirection.value === 'csv-to-excel' ||
         csvDirection.value === 'tsv-to-excel' ||
         csvDirection.value === 'text-to-excel'
}

// 检查是否需要文本输入
function needTextInput(): boolean {
  return csvDirection.value === 'json-to-excel' ||
         csvDirection.value === 'text-to-excel'
}

// 获取上传文件类型
function getAcceptTypes(): string {
  switch (csvDirection.value) {
    case 'xml-to-excel':
      return '.xml'
    case 'yaml-to-excel':
      return '.yaml,.yml'
    case 'csv-to-excel':
      return '.csv'
    case 'tsv-to-excel':
      return '.tsv'
    case 'text-to-excel':
      return '.txt'
    case 'excel-to-json':
      return '.xlsx,.xls'
    default:
      return '.csv,.xlsx,.xls,.xml,.yaml,.yml,.tsv,.txt,.json'
  }
}

// 获取上传按钮文本
function getUploadButtonText(): string {
  switch (csvDirection.value) {
    case 'xml-to-excel':
      return '选择XML文件'
    case 'yaml-to-excel':
      return '选择YAML文件'
    case 'csv-to-excel':
      return '选择CSV文件'
    case 'tsv-to-excel':
      return '选择TSV文件'
    case 'text-to-excel':
      return '选择文本文件'
    case 'excel-to-json':
      return '选择Excel文件'
    default:
      return '选择文件'
  }
}

// 获取上传提示文本
function getUploadTipText(): string {
  switch (csvDirection.value) {
    case 'xml-to-excel':
      return '支持 .xml 格式文件'
    case 'yaml-to-excel':
      return '支持 .yaml, .yml 格式文件'
    case 'csv-to-excel':
      return '支持 .csv 格式文件'
    case 'tsv-to-excel':
      return '支持 .tsv 格式文件'
    case 'text-to-excel':
      return '支持 .txt 格式文件'
    case 'excel-to-json':
      return '支持 .xlsx, .xls 格式文件'
    default:
      return '支持多种格式文件'
  }
}

// 获取转换按钮文本
function getConvertButtonText(): string {
  switch (csvDirection.value) {
    case 'url-to-excel':
      return '获取并转换'
    case 'excel-to-json':
      return '转换为JSON'
    default:
      return '转换为Excel'
  }
}

// 测试URL连接
async function testUrl() {
  if (!urlInput.value.trim()) {
    ElMessage.warning('请输入URL地址')
    return
  }

  loading.value = true
  try {
    const response = await fetch(urlInput.value, {
      method: urlOptions.value.method,
      headers: {
        'Content-Type': 'application/json',
      },
      body: urlOptions.value.method === 'POST' ? urlOptions.value.body : undefined
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const data = await response.text()
    uploadedFileContent.value = data
    ElMessage.success('URL数据获取成功')
  } catch (error) {
    ElMessage.error('URL访问失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 清空所有数据
function clearAll() {
  csvInput.value = ''
  csvOutput.value = ''
  uploadedFileContent.value = ''
  urlInput.value = ''
  previewData.value = []
  previewColumns.value = []
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 下载CSV文件
function downloadAsCSV() {
  if (!csvOutput.value) {
    ElMessage.warning('没有可下载的内容')
    return
  }

  const blob = new Blob([csvOutput.value], { type: 'text/csv' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${excelOptions.value.sheetName}.csv`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  ElMessage.success('CSV文件下载完成')
}

// JSON/XML转换功能
function convertJsonXml() {
  if (!jsonXmlInput.value.trim()) {
    ElMessage.warning('请输入要转换的数据')
    return
  }
  
  loading.value = true
  setTimeout(() => {
    try {
      if (jsonXmlDirection.value === 'json-to-xml') {
        // JSON转XML
        const jsonData = JSON.parse(jsonXmlInput.value)
        jsonXmlOutput.value = jsonToXml(jsonData)
        ElMessage.success('JSON转XML完成')
      } else {
        // XML转JSON
        const jsonData = xmlToJson(jsonXmlInput.value)
        jsonXmlOutput.value = JSON.stringify(jsonData, null, 2)
        ElMessage.success('XML转JSON完成')
      }
    } catch (error) {
      ElMessage.error('转换失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

function validateInput() {
  if (!jsonXmlInput.value.trim()) {
    ElMessage.warning('请输入要验证的数据')
    return
  }
  
  try {
    if (jsonXmlDirection.value === 'json-to-xml') {
      JSON.parse(jsonXmlInput.value)
      ElMessage.success('JSON格式正确')
    } else {
      // 简单的XML验证
      const parser = new DOMParser()
      const doc = parser.parseFromString(jsonXmlInput.value, 'text/xml')
      const errorNode = doc.querySelector('parsererror')
      if (errorNode) {
        throw new Error('XML格式错误')
      }
      ElMessage.success('XML格式正确')
    }
  } catch (error) {
    ElMessage.error('格式验证失败：' + error.message)
  }
}

// YAML转换功能
function convertYaml() {
  if (!yamlInput.value.trim()) {
    ElMessage.warning('请输入要转换的数据')
    return
  }
  
  loading.value = true
  setTimeout(() => {
    try {
      if (yamlDirection.value === 'json-to-yaml') {
        // JSON转YAML
        const jsonData = JSON.parse(yamlInput.value)
        yamlOutput.value = jsonToYaml(jsonData, yamlOptions.value.indent)
        ElMessage.success('JSON转YAML完成')
      } else {
        // YAML转JSON（简化实现）
        const jsonData = yamlToJson(yamlInput.value)
        yamlOutput.value = JSON.stringify(jsonData, null, 2)
        ElMessage.success('YAML转JSON完成')
      }
    } catch (error) {
      ElMessage.error('转换失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

// CSV转换功能
function convertToExcel() {
  let inputData = ''
  
  console.log('转换方向:', csvDirection.value)
  console.log('上传文件内容:', uploadedFileContent.value)
  console.log('文本输入内容:', csvInput.value)
  
  // 根据转换方向确定数据来源
  if (csvDirection.value === 'excel-to-json') {
    // Excel转JSON - 需要上传文件
    inputData = uploadedFileContent.value
  } else if (csvDirection.value === 'url-to-excel') {
    // URL转Excel - 从URL获取的数据
    inputData = uploadedFileContent.value
  } else if (csvDirection.value === 'json-to-excel' || csvDirection.value === 'text-to-excel') {
    // JSON转Excel 或 文本转Excel - 需要文本输入
    inputData = csvInput.value
  } else {
    // 其他类型（xml、yaml、csv、tsv转Excel） - 需要上传文件
    inputData = uploadedFileContent.value
  }
  
  console.log("最终输入数据:",inputData)
  if (!inputData || !inputData.trim()) {
    ElMessage.warning('请输入要转换的数据或上传文件')
    return
  }
  
  loading.value = true
  setTimeout(() => {
    try {
      let processedData = []
      
      switch (csvDirection.value) {
        case 'json-to-excel':
          // JSON转Excel
          const jsonData = JSON.parse(inputData)
          if (!Array.isArray(jsonData)) {
            throw new Error('JSON数据必须是数组格式')
          }
          processedData = jsonData
          csvOutput.value = jsonToExcel(processedData, excelOptions.value)
          ElMessage.success('JSON转Excel完成')
          break
          
        case 'xml-to-excel':
          // XML转Excel
          const xmlData = xmlToJson(inputData)
          // 将XML对象转换为表格数组
          processedData = xmlToTableData(xmlData)
          csvOutput.value = jsonToExcel(processedData, excelOptions.value)
          ElMessage.success('XML转Excel完成')
          break
          
        case 'yaml-to-excel':
          // YAML转Excel
          const yamlData = yamlToJson(inputData)
          // 将YAML对象转换为表格数组
          processedData = objectToTableData(yamlData)
          csvOutput.value = jsonToExcel(processedData, excelOptions.value)
          ElMessage.success('YAML转Excel完成')
          break
          
        case 'csv-to-excel':
          // CSV转Excel
          processedData = csvToJson(inputData, { delimiter: ',', header: excelOptions.value.includeHeader })
          csvOutput.value = jsonToExcel(processedData, excelOptions.value)
          ElMessage.success('CSV转Excel完成')
          break
          
        case 'tsv-to-excel':
          // TSV转Excel
          processedData = csvToJson(inputData, { delimiter: '\t', header: excelOptions.value.includeHeader })
          csvOutput.value = jsonToExcel(processedData, excelOptions.value)
          ElMessage.success('TSV转Excel完成')
          break
          
        case 'text-to-excel':
          // 文本转Excel
          processedData = textToTableData(inputData, textOptions.value)
          csvOutput.value = jsonToExcel(processedData, excelOptions.value)
          ElMessage.success('文本转Excel完成')
          break
          
        case 'excel-to-json':
          // Excel转JSON
          let excelJsonData
          if (uploadedFileContent.value.startsWith('[') || uploadedFileContent.value.startsWith('{')) {
            // 已经是JSON格式（从Excel读取后转换的）
            excelJsonData = JSON.parse(uploadedFileContent.value)
          } else {
            // 作为CSV处理
            excelJsonData = csvToJson(uploadedFileContent.value, { delimiter: ',', header: true })
          }
          csvOutput.value = JSON.stringify(excelJsonData, null, 2)
          processedData = Array.isArray(excelJsonData) ? excelJsonData : [excelJsonData]
          ElMessage.success('Excel转JSON完成')
          break
          
        case 'url-to-excel':
          // URL数据转Excel
          try {
            // 尝试解析为JSON
            const urlJsonData = JSON.parse(inputData)
            if (Array.isArray(urlJsonData)) {
              processedData = urlJsonData
            } else {
              processedData = [urlJsonData]
            }
          } catch {
            // 如果不是JSON，尝试作为CSV处理
            processedData = csvToJson(inputData, { delimiter: ',', header: excelOptions.value.includeHeader })
          }
          csvOutput.value = jsonToExcel(processedData, excelOptions.value)
          ElMessage.success('URL数据转Excel完成')
          break
          
        default:
          throw new Error('不支持的转换类型')
      }
      
      // 设置预览数据
      setPreviewData(processedData)
      
    } catch (error) {
      ElMessage.error('转换失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

// 设置预览数据
function setPreviewData(data: any[]) {
  if (!data || data.length === 0) {
    previewData.value = []
    previewColumns.value = []
    return
  }
  
  previewData.value = data
  
  // 生成列配置
  const firstRow = data[0]
  if (typeof firstRow === 'object' && firstRow !== null) {
    previewColumns.value = Object.keys(firstRow).map(key => ({
      prop: key,
      label: key,
      width: 150
    }))
  } else {
    // 如果是简单数组，创建默认列
    previewColumns.value = [
      { prop: 'value', label: '值', width: 150 }
    ]
    previewData.value = data.map(item => ({ value: item }))
  }
}

// XML转表格数据
function xmlToTableData(xmlData: any): any[] {
  if (Array.isArray(xmlData)) {
    return xmlData
  }
  
  // 如果是对象，尝试找到数组字段
  for (const key in xmlData) {
    if (Array.isArray(xmlData[key])) {
      return xmlData[key]
    }
  }
  
  // 如果没有数组，将对象转换为单行数据
  return [xmlData]
}

// 对象转表格数据
function objectToTableData(data: any): any[] {
  if (Array.isArray(data)) {
    return data
  }
  
  if (typeof data === 'object' && data !== null) {
    return [data]
  }
  
  return [{ value: data }]
}

// 文本转表格数据
function textToTableData(text: string, options: any): any[] {
  const lines = text.split('\n').filter(line => line.trim())
  
  if (options.splitByLine && !options.splitBySpace && !options.splitByComma && !options.customDelimiter) {
    // 只按行分割，每行作为一个值
    return lines.map((line, index) => ({ [`行${index + 1}`]: line.trim() }))
  }
  
  const result = []
  
  for (const line of lines) {
    let cells = [line]
    
    if (options.customDelimiter) {
      cells = line.split(options.customDelimiter)
    } else if (options.splitByComma) {
      cells = line.split(',')
    } else if (options.splitBySpace) {
      cells = line.split(/\s+/)
    }
    
    // 创建行对象
    const row: any = {}
    cells.forEach((cell, index) => {
      row[`列${index + 1}`] = cell.trim()
    })
    
    result.push(row)
  }
  
  return result
}

// 数据格式化功能
function formatData() {
  if (!formatInput.value.trim()) {
    ElMessage.warning('请输入要格式化的数据')
    return
  }
  
  loading.value = true
  setTimeout(() => {
    try {
      const indent = formatOptions.value.indent === 'tab' ? '\t' : formatOptions.value.indent
      
      switch (formatType.value) {
        case 'json':
          const jsonData = JSON.parse(formatInput.value)
          formatOutput.value = JSON.stringify(jsonData, null, indent)
          break
        case 'xml':
          formatOutput.value = formatXml(formatInput.value, indent)
          break
        case 'sql':
          formatOutput.value = formatSql(formatInput.value)
          break
        case 'css':
          formatOutput.value = formatCss(formatInput.value)
          break
        case 'html':
          formatOutput.value = formatHtml(formatInput.value)
          break
        default:
          throw new Error('不支持的格式类型')
      }
      
      ElMessage.success('格式化完成')
    } catch (error) {
      ElMessage.error('格式化失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

function minifyData() {
  if (!formatInput.value.trim()) {
    ElMessage.warning('请输入要压缩的数据')
    return
  }
  
  loading.value = true
  setTimeout(() => {
    try {
      switch (formatType.value) {
        case 'json':
          const jsonData = JSON.parse(formatInput.value)
          formatOutput.value = JSON.stringify(jsonData)
          break
        case 'xml':
          formatOutput.value = minifyXml(formatInput.value)
          break
        case 'css':
          formatOutput.value = minifyCss(formatInput.value)
          break
        case 'html':
          formatOutput.value = minifyHtml(formatInput.value)
          break
        default:
          formatOutput.value = formatInput.value.replace(/\s+/g, ' ').trim()
      }
      
      ElMessage.success('压缩完成')
    } catch (error) {
      ElMessage.error('压缩失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

// 转换工具函数
function jsonToXml(obj: any, rootName = 'root'): string {
  let xml = ''
  
  if (xmlOptions.value.declaration) {
    xml += '<?xml version="1.0" encoding="UTF-8"?>\n'
  }
  
  function convertValue(value: any, key: string, level = 0): string {
    const indent = xmlOptions.value.pretty ? '  '.repeat(level) : ''
    const newline = xmlOptions.value.pretty ? '\n' : ''
    
    if (value === null || value === undefined) {
      return `${indent}<${key}></${key}>${newline}`
    }
    
    if (typeof value === 'object') {
      if (Array.isArray(value)) {
        return value.map(item => convertValue(item, key, level)).join('')
      } else {
        let result = `${indent}<${key}>${newline}`
        for (const [k, v] of Object.entries(value)) {
          result += convertValue(v, k, level + 1)
        }
        result += `${indent}</${key}>${newline}`
        return result
      }
    } else {
      return `${indent}<${key}>${String(value)}</${key}>${newline}`
    }
  }
  
  xml += convertValue(obj, rootName)
  return xml
}

function xmlToJson(xmlString: string): any {
  const parser = new DOMParser()
  const doc = parser.parseFromString(xmlString, 'text/xml')
  
  function parseNode(node: any): any {
    if (node.nodeType === Node.TEXT_NODE) {
      return node.textContent?.trim() || ''
    }
    
    const result: any = {}
    
    // 处理属性
    if (node.attributes) {
      for (const attr of node.attributes) {
        result[`@${attr.name}`] = attr.value
      }
    }
    
    // 处理子节点
    const children: any = {}
    for (const child of node.childNodes) {
      if (child.nodeType === Node.ELEMENT_NODE) {
        const childName = child.nodeName
        const childValue = parseNode(child)
        
        if (children[childName]) {
          if (!Array.isArray(children[childName])) {
            children[childName] = [children[childName]]
          }
          children[childName].push(childValue)
        } else {
          children[childName] = childValue
        }
      } else if (child.nodeType === Node.TEXT_NODE) {
        const text = child.textContent?.trim()
        if (text) {
          result['#text'] = text
        }
      }
    }
    
    return Object.keys(children).length > 0 ? { ...result, ...children } : result
  }
  
  return parseNode(doc.documentElement)
}

function jsonToYaml(obj: any, indent = 2): string {
  function convertValue(value: any, level = 0): string {
    const spaces = ' '.repeat(level * indent)
    
    if (value === null || value === undefined) {
      return 'null'
    }
    
    if (typeof value === 'string') {
      return `"${value}"`
    }
    
    if (typeof value === 'number' || typeof value === 'boolean') {
      return String(value)
    }
    
    if (Array.isArray(value)) {
      if (value.length === 0) return '[]'
      return '\n' + value.map(item => 
        `${spaces}- ${convertValue(item, level + 1).replace(/^\n/, '')}`
      ).join('\n')
    }
    
    if (typeof value === 'object') {
      const entries = Object.entries(value)
      if (entries.length === 0) return '{}'
      return '\n' + entries.map(([key, val]) => 
        `${spaces}${key}: ${convertValue(val, level + 1).replace(/^\n/, '')}`
      ).join('\n')
    }
    
    return String(value)
  }
  
  return convertValue(obj).replace(/^\n/, '')
}

function yamlToJson(yamlString: string): any {
  // 简化的YAML解析器（实际项目中建议使用专业的YAML库）
  const lines = yamlString.split('\n').filter(line => line.trim())
  const result: any = {}
  
  for (const line of lines) {
    const trimmed = line.trim()
    if (trimmed.includes(':')) {
      const [key, ...valueParts] = trimmed.split(':')
      const value = valueParts.join(':').trim()
      
      if (value.startsWith('"') && value.endsWith('"')) {
        result[key.trim()] = value.slice(1, -1)
      } else if (value === 'true' || value === 'false') {
        result[key.trim()] = value === 'true'
      } else if (!isNaN(Number(value))) {
        result[key.trim()] = Number(value)
      } else {
        result[key.trim()] = value || null
      }
    }
  }
  
  return result
}

function jsonToCsv(jsonArray: any[], options: any): string {
  if (jsonArray.length === 0) return ''
  
  const headers = Object.keys(jsonArray[0])
  let csv = ''
  
  if (options.header) {
    csv += headers.join(options.delimiter) + '\n'
  }
  
  for (const row of jsonArray) {
    const values = headers.map(header => {
      const value = row[header]
      if (typeof value === 'string' && (value.includes(options.delimiter) || value.includes('\n'))) {
        return `"${value.replace(/"/g, '""')}"`
      }
      return value
    })
    csv += values.join(options.delimiter) + '\n'
  }
  
  return csv
}

function csvToJson(csvString: string, options: any): any[] {
  const lines = csvString.split('\n').filter(line => line.trim())
  if (lines.length === 0) return []
  
  const headers = options.header ? 
    lines[0].split(options.delimiter).map(h => h.trim()) :
    Array.from({ length: lines[0].split(options.delimiter).length }, (_, i) => `column${i + 1}`)
  
  const dataLines = options.header ? lines.slice(1) : lines
  
  return dataLines.map(line => {
    const values = line.split(options.delimiter)
    const obj: any = {}
    headers.forEach((header, index) => {
      obj[header] = values[index]?.trim() || ''
    })
    return obj
  })
}

function formatXml(xmlString: string, indent: any): string {
  // 简化的XML格式化
  return xmlString.replace(/></g, '>\n<').replace(/\n\s*\n/g, '\n')
}

function formatSql(sqlString: string): string {
  // 简化的SQL格式化
  return sqlString
    .replace(/\bSELECT\b/gi, '\nSELECT')
    .replace(/\bFROM\b/gi, '\nFROM')
    .replace(/\bWHERE\b/gi, '\nWHERE')
    .replace(/\bORDER BY\b/gi, '\nORDER BY')
    .replace(/\bGROUP BY\b/gi, '\nGROUP BY')
    .trim()
}

function formatCss(cssString: string): string {
  // 简化的CSS格式化
  return cssString
    .replace(/\{/g, ' {\n  ')
    .replace(/\}/g, '\n}\n')
    .replace(/;/g, ';\n  ')
    .replace(/\n\s*\n/g, '\n')
}

function formatHtml(htmlString: string): string {
  // 简化的HTML格式化
  return htmlString.replace(/></g, '>\n<')
}

function minifyXml(xmlString: string): string {
  return xmlString.replace(/>\s+</g, '><').trim()
}

function minifyCss(cssString: string): string {
  return cssString.replace(/\s+/g, ' ').replace(/;\s*}/g, '}').trim()
}

function minifyHtml(htmlString: string): string {
  return htmlString.replace(/>\s+</g, '><').trim()
}

// 清空函数
function clearJsonXml() {
  jsonXmlInput.value = ''
  jsonXmlOutput.value = ''
}

function clearYaml() {
  yamlInput.value = ''
  yamlOutput.value = ''
}

function clearFormat() {
  formatInput.value = ''
  formatOutput.value = ''
}

function clearOutput(type: string) {
  switch (type) {
    case 'jsonXml':
      jsonXmlOutput.value = ''
      break
    case 'yaml':
      yamlOutput.value = ''
      break
    case 'csv':
      csvOutput.value = ''
      break
    case 'format':
      formatOutput.value = ''
      break
  }
  ElMessage.info('已清空结果')
}

// 复制和下载函数
function copyResult(type: string) {
  let text = ''
  switch (type) {
    case 'jsonXml':
      text = jsonXmlOutput.value
      break
    case 'yaml':
      text = yamlOutput.value
      break
    case 'csv':
      text = csvOutput.value
      break
    case 'format':
      text = formatOutput.value
      break
  }
  
  if (text) {
    navigator.clipboard.writeText(text)
    ElMessage.success('结果已复制到剪贴板')
  } else {
    ElMessage.warning('没有可复制的内容')
  }
}

function downloadResult(type: string) {
  let content = ''
  let filename = ''
  let mimeType = 'text/plain'
  
  switch (type) {
    case 'jsonXml':
      content = jsonXmlOutput.value
      filename = jsonXmlDirection.value === 'json-to-xml' ? 'converted.xml' : 'converted.json'
      mimeType = jsonXmlDirection.value === 'json-to-xml' ? 'text/xml' : 'application/json'
      break
    case 'yaml':
      content = yamlOutput.value
      filename = yamlDirection.value === 'json-to-yaml' ? 'converted.yaml' : 'converted.json'
      mimeType = yamlDirection.value === 'json-to-yaml' ? 'text/yaml' : 'application/json'
      break
    case 'csv':
      content = csvOutput.value
      // 根据转换方向确定文件名和类型
      if (csvDirection.value === 'json-to-csv') {
        filename = 'converted.csv'
        mimeType = 'text/csv'
      } else if (csvDirection.value === 'csv-to-json') {
        filename = 'converted.json'
        mimeType = 'application/json'
      } else if (csvDirection.value.includes('to-excel')) {
        // 所有转换为Excel的情况
        filename = `${excelOptions.value.sheetName}.xls`
        mimeType = 'application/vnd.ms-excel'
      } else if (csvDirection.value === 'excel-to-json') {
        filename = 'converted.json'
        mimeType = 'application/json'
      } else {
        // 其他Excel相关转换
        filename = `${excelOptions.value.sheetName}.xls`
        mimeType = 'application/vnd.ms-excel'
      }
      break
    case 'format':
      content = formatOutput.value
      filename = `formatted.${formatType.value}`
      break
  }
  
  if (content) {
    const blob = new Blob([content], { type: mimeType })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    ElMessage.success('文件下载完成')
  } else {
    ElMessage.warning('没有可下载的内容')
  }
}

// Excel工具函数
function jsonToExcel(jsonArray: any[], options: any): string {
  if (jsonArray.length === 0) return ''
  
  // 创建工作簿和工作表
  const workbook = createWorkbook()
  const headers = Object.keys(jsonArray[0])
  
  // 准备数据
  const data = []
  if (csvOptions.value.header) {
    data.push(headers)
  }
  
  jsonArray.forEach(row => {
    const rowData = headers.map(header => row[header] || '')
    data.push(rowData)
  })
  
  // 创建工作表
  const worksheet = createWorksheet(data)
  workbook.Sheets[options.sheetName] = worksheet
  workbook.SheetNames = [options.sheetName]
  
  // 返回Excel文件的Base64编码
  return writeExcelFile(workbook)
}

function readExcelFile(data: Uint8Array): any {
  // 简化的Excel读取实现
  // 实际项目中建议使用 SheetJS 库
  try {
    const decoder = new TextDecoder('utf-8')
    const csvContent = decoder.decode(data)
    
    // 如果是CSV文件，直接返回模拟的workbook结构
    if (csvContent.includes(',') || csvContent.includes(';')) {
      return {
        SheetNames: ['Sheet1'],
        Sheets: {
          'Sheet1': csvToWorksheet(csvContent)
        }
      }
    }
    
    throw new Error('暂不支持此Excel格式，请使用CSV格式或更新的Excel文件')
  } catch (error) {
    throw new Error('Excel文件读取失败：' + error.message)
  }
}

function csvToWorksheet(csvContent: string): any {
  const lines = csvContent.split('\n').filter(line => line.trim())
  const data: any = {}
  
  lines.forEach((line, rowIndex) => {
    const cells = line.split(csvOptions.value.delimiter)
    cells.forEach((cell, colIndex) => {
      const cellAddress = getCellAddress(rowIndex, colIndex)
      data[cellAddress] = { v: cell.trim(), t: 's' }
    })
  })
  
  data['!ref'] = `A1:${getCellAddress(lines.length - 1, lines[0].split(csvOptions.value.delimiter).length - 1)}`
  return data
}

function sheetToJson(worksheet: any): any[] {
  if (!worksheet['!ref']) return []
  
  const range = parseRange(worksheet['!ref'])
  const result: any[] = []
  
  for (let row = range.s.r; row <= range.e.r; row++) {
    const rowData: any = {}
    for (let col = range.s.c; col <= range.e.c; col++) {
      const cellAddress = getCellAddress(row, col)
      const cell = worksheet[cellAddress]
      const colName = String.fromCharCode(65 + col) // A, B, C...
      rowData[colName] = cell ? cell.v : ''
    }
    result.push(rowData)
  }
  
  return result
}

function createWorkbook(): any {
  return {
    SheetNames: [],
    Sheets: {}
  }
}

function createWorksheet(data: any[][]): any {
  const worksheet: any = {}
  const range = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } }
  
  data.forEach((row, rowIndex) => {
    row.forEach((cell, colIndex) => {
      const cellAddress = getCellAddress(rowIndex, colIndex)
      worksheet[cellAddress] = { v: cell, t: typeof cell === 'number' ? 'n' : 's' }
      
      if (colIndex > range.e.c) range.e.c = colIndex
      if (rowIndex > range.e.r) range.e.r = rowIndex
    })
  })
  
  worksheet['!ref'] = `A1:${getCellAddress(range.e.r, range.e.c)}`
  return worksheet
}

// XML转义函数
function escapeXml(text: string): string {
  return text.replace(/&/g, '&amp;')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;')
             .replace(/"/g, '&quot;')
             .replace(/'/g, '&apos;')
}

function writeExcelFile(workbook: any): string {
  // 生成Excel XML格式 - 兼容Excel 2003及以上版本
  const sheetName = workbook.SheetNames[0]
  const worksheet = workbook.Sheets[sheetName]
  
  if (!worksheet['!ref']) return ''
  
  const range = parseRange(worksheet['!ref'])
  
  // 构建Excel XML头部
  let xmlContent = `<?xml version="1.0" encoding="UTF-8"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Created>${new Date().toISOString()}</Created>
 </DocumentProperties>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font ss:FontName="宋体" x:CharSet="134" ss:Size="12"/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
  <Style ss:ID="Header">
   <Font ss:FontName="宋体" x:CharSet="134" ss:Size="12" ss:Bold="1"/>
   <Interior ss:Color="#E6E6FA" ss:Pattern="Solid"/>
  </Style>
 </Styles>
 <Worksheet ss:Name="${sheetName}">
  <Table>
`

  // 添加数据行
  for (let row = range.s.r; row <= range.e.r; row++) {
    xmlContent += '   <Row>'
    for (let col = range.s.c; col <= range.e.c; col++) {
      const cellAddress = getCellAddress(row, col)
      const cell = worksheet[cellAddress]
      const cellValue = cell ? String(cell.v) : ''
      const styleId = row === 0 && excelOptions.value.includeHeader ? 'Header' : 'Default'
      
      // 判断数据类型
      const isNumber = !isNaN(Number(cellValue)) && cellValue !== ''
      const dataType = isNumber ? 'Number' : 'String'
      
      xmlContent += `
    <Cell ss:StyleID="${styleId}">
     <Data ss:Type="${dataType}">${escapeXml(cellValue)}</Data>
    </Cell>`
    }
    xmlContent += '\n   </Row>'
  }

  // 添加XML尾部
  xmlContent += `
  </Table>
 </Worksheet>
</Workbook>`

  return xmlContent
}

function getCellAddress(row: number, col: number): string {
  return String.fromCharCode(65 + col) + (row + 1)
}

function parseRange(range: string): any {
  const [start, end] = range.split(':')
  return {
    s: { r: parseInt(start.slice(1)) - 1, c: start.charCodeAt(0) - 65 },
    e: { r: parseInt(end.slice(1)) - 1, c: end.charCodeAt(0) - 65 }
  }
}
</script>

<style scoped>
.format-tools {
  position: relative;
}

.convert-section,
.yaml-section,
.csv-section,
.format-section {
  width: 100%;
}

.result-display {
  width: 100%;
}

.result-display h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary, #303133);
}

.result-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .result-actions {
    flex-direction: column;
  }
}

.preview-section {
  margin-bottom: 20px;
  padding: 16px;
  background-color: var(--el-bg-color-page, #f5f7fa);
  border-radius: 8px;
}

.preview-section h5 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: var(--el-text-color-primary, #303133);
  font-weight: 600;
}

.preview-info {
  margin: 0;
  font-size: 12px;
  color: var(--el-text-color-secondary, #909399);
}
</style> 